﻿using CommonType;
using MediatR;
using MySqlX.XDevAPI.Common;
using S_Examine.Domains.Entity;
using S_Examine.Infrastructure.DapperInterface;
using S_Examine.Read.API.Application.Commands.AssessmentIndexCommand;

namespace S_Examine.Read.API.Application.CommandHandlers.AssessmentIndexHandler
{
	public class AssessmentIndexQueryCommandHandler : IRequestHandler<AssessmentIndexQueryCommand, ApiResule<PageResule<AssessmentIndex>>>
	{
		private readonly IDapperAssessmentIndexRepository _dapperAssessmentIndexRepository;

		public AssessmentIndexQueryCommandHandler(IDapperAssessmentIndexRepository dapperAssessmentIndexRepository)
		{
			_dapperAssessmentIndexRepository = dapperAssessmentIndexRepository;
		}

		public async Task<ApiResule<PageResule<AssessmentIndex>>> Handle(AssessmentIndexQueryCommand request, CancellationToken cancellationToken)
		{
			// 构建模糊查询条件
			string condition = string.IsNullOrWhiteSpace(request.indexName) ? "" : $"WHERE IndexName LIKE CONCAT('%', {request.indexName}, '%')";

			// 构建 SQL 查询语句
			string sql = $@"
            SELECT *
            FROM Assessmentindex
            {condition}
            ORDER BY Id DESC
            LIMIT @offset, @pageSize;
        ";

			// 获取总条数
			int totalCount = await _dapperAssessmentIndexRepository.GetTotalCountAsync(condition, request.indexName);

			// 计算总页数
			int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);

			// 执行分页查询
			var assessment = await _dapperAssessmentIndexRepository.GetPageAsync(request.pageSize, request.pageIndex, sql, request.indexName);

			return new ApiResule<PageResule<AssessmentIndex>>
			{
				Code = 200,
				Msg = "成功",
				Result = new PageResule<AssessmentIndex>
				{
					TotalCount = totalCount,
					PageCount = pageCount,
					Data = assessment.ToList()
				}
			};
		}
	}

}
